import React, {useState, useEffect} from 'react';
import styles from './App.module.css';
import logo from './assets/images/react.svg';
import Robot from "./components/Robot.tsx";
import RobotDiscount from "./components/RobotDiscount.tsx";
import ShoppingCart from "./components/ShoppingCart.tsx";

interface Props {
}

interface State {
    robotGallery: [];
    count: number;
}

const App: React.FC = (props) => {
    const [count, setCount] = useState<number>(0);
    const [robotGallery, setRobotGallery] = useState([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<string>();

    useEffect(() => {
        document.title = `点击${count}次`
    }, [count])

    useEffect(() => {
        setLoading(true)
        const fetchData = async () => {
            try {
                const response = await fetch("https://jsonplaceholder.typicode.com/users");
                const data = await response.json();
                setRobotGallery(data);
            } catch (e) {
                setError(e.message)
            }
            setLoading(false)
        }
        fetchData()
    }, [])

    return (
        <>
            <div className={styles.app}>
                <div className={styles.appHeader}>
                    <img src={logo} alt="logo"/>
                    <h1>罗伯特机器人炫酷吊炸天online购物平台名字要长</h1>
                </div>
                <button onClick={() => {
                    setCount(count + 1)
                }}>Click
                </button>
                <span>count:{count}</span>
                <ShoppingCart/>
                {!error || error !== "" && <div>网站出错：{error}</div>}
                {
                    !loading ? (
                        <div className={styles.robotList}>
                            {robotGallery.map((r, index) => index % 2 == 0 ? (
                                <RobotDiscount id={r.id} email={r.email} name={r.name}/>
                            ) : (
                                <Robot id={r.id} email={r.email} name={r.name}/>
                            ))}
                        </div>
                    ) : (
                        <h2>loading 加载中...</h2>
                    )
                }
            </div>
        </>
    )
}

export default App